var express = require('express');
var router = express.Router();
var md5 = require('md5');
const UserModel = require('../../models/UserModel')

/* 注册页面 */
router.get('/register', (req, res, next) => {
  res.render('auth/register', { title: '注册' });
})

/** 注册用户 */
router.post('/register', (req, res, next) => {
  UserModel.create({
    ...req.body,
    password: md5(req.body.password)
  }).then(() => {
    res.render('success', { msg: '注册成功', url: '/login' })
  }).catch(() => {
    res.status(500).send('注册失败')
  })
})

/** 登录页面 */
router.get('/login', (req, res, next) => {
  res.render('auth/login')
})

/** 登录操作 */
router.post('/login', (req, res, next) => {
  const { username, password } = req.body
  UserModel.findOne({
    username: username,
    password: md5(password)
  }).then(user => {
    console.log('user1: ', user);
    
    if (user) {
      // 写入 session
      req.session.username = user.username;
      req.session._id = user._id;
      res.render('success', { msg: '登录成功', url: '/account'})
    } else {
      res.send('用户名或者密码错误！')
    }
  }).catch(() => {
    res.status(500).send('登录失败1')
  })
})

/** 退出操作 */
router.post('/logout', (req, res) => {
  req.session.destroy(() => {
    res.render('success', { msg: '退出成功', url: '/login'})
  })
})

module.exports = router;
